package org.mspring.mlog.duoshuo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.mspring.mlog.duoshuo.entity.DuoshuoSyncLog;
import org.mspring.mlog.duoshuo.service.DuoshuoSyncLogService;
import org.mspring.mlog.duoshuo.sync.SyncHandler;
import org.mspring.mlog.duoshuo.sync.SyncRequest;
import org.mspring.mlog.duoshuo.sync.SyncResponse;
import org.mspring.nbee.common.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 多说
 *
 * @author Gao Youbo
 * @since 2015-02-13 18:06
 */
public class DuoshuoService {
    private static final Logger LOG = LoggerFactory.getLogger(DuoshuoService.class);

    private static final String IMPORT_URL = "http://api.duoshuo.com/posts/import.json";
    private static final String LIST_URL = "http://api.duoshuo.com/log/list.json";

    private String shortName;
    private String secret;
    private DuoshuoSyncLogService duoshuoSyncLogService;

    public static void main(String[] args) throws ParseException {
        DuoshuoService service = new DuoshuoService();
        service.setShortName("mspring");
        service.setSecret("b80f85b12b395f1fbed0acac98081282");
        service.sync(new SyncHandler() {
            @Override
            public void handle(SyncResponse response) {
                System.out.println(response.getMeta());
            }
        });

        String time = "2015-02-14T18:19:09+08:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(time);
        String formattedTime = output.format(d);
        System.out.println(formattedTime);
    }


    /**
     * 导入评论
     *
     * @param posts 根据多说请求参数封装后的评论实体
     */
    public void importComment(List<ImportRequest.Post> posts) {
        if (posts == null || posts.isEmpty()) {
            return;
        }
        ImportRequest request = new ImportRequest();
        request.setShortName(shortName);
        request.setSecret(secret);
        request.getPosts().addAll(posts);
        List<NameValuePair> nvps = request.buildParams();
        HttpUtils.httpPost(IMPORT_URL, nvps);
    }

    public void sync(SyncHandler syncHandler) {
        long sinceId = duoshuoSyncLogService.findLastLogId();
        SyncRequest request = new SyncRequest();
        request.setShortName(shortName);
        request.setSecret(secret);
        request.setOrder("asc");
        request.setSinceId(sinceId);
        LOG.info("同步多说评论...{}", request.toString());

        List<NameValuePair> nvps = request.buildParams();
        String result = HttpUtils.httpGet(LIST_URL, nvps);
        JSONObject json = JSON.parseObject(result);
        int code = json.getIntValue("code");
        if (code != 0) {
            String errorMessage = json.getString("errorMessage");
            LOG.error("同步失败,code={}, errorMessage={}", code, errorMessage);
            return;
        }
        JSONArray response = json.getJSONArray("response");
        if (response != null && !response.isEmpty()) {
            for (int i = 0; i < response.size(); i++) {
                boolean success = true;
                SyncResponse rsp = SyncResponse.fromJsonObject(response.getJSONObject(i));
                try {
                    syncHandler.handle(rsp);
                } catch (Exception e) {
                    LOG.error(null, e);
                    success = false;
                } finally {
                    //插入同步日志
                    DuoshuoSyncLog syncLog = new DuoshuoSyncLog();
                    syncLog.setLogId(rsp.getLogId());
                    syncLog.setUserId(rsp.getUserId());
                    syncLog.setAction(rsp.getAction().getValue());
                    syncLog.setDate(rsp.getDate());
                    syncLog.setMeta(rsp.getMeta());
                    syncLog.setSuccess(success);
                    syncLog.setCreateTime(new Date());
                    duoshuoSyncLogService.insert(syncLog);
                }
            }
        }
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public void setDuoshuoSyncLogService(DuoshuoSyncLogService duoshuoSyncLogService) {
        this.duoshuoSyncLogService = duoshuoSyncLogService;
    }
}
